# _*_ coding:utf-8 _*_
# By:赵先宇
from src.engine.base import BaseHandler
from ..plugins import get_server_info
import requests
import json, os
from lib.conf.config import settings
import time
from lib.auth import gen_key


class AgentHandler(BaseHandler):

    def cmd(self, command, hostname):
        import subprocess
        ret = subprocess.getoutput(command)
        return ret

    def handler(self):
        """
        Agent模式采集资产
        :return:
        """
        # 采集硬盘、内存、网卡
        info = get_server_info(self)

        # 主机标识
        cert_path = settings.CERT_PATH
        if not os.path.exists(cert_path):
            # 如果没有这个文件 当前是新增主机
            info['type'] = 'create'
        else:
            # 修改
            with open(cert_path, 'r', encoding='utf-8') as f:
                cert = f.read()  # 原主机名
            hostname = info['basic']['data']['hostname']

            if cert == hostname:  # 判断本地文件的唯一标识 是不是等于 获取的基本信息里主机名
                # 更新资产
                info['type'] = 'update'  # 一样就更新资产信息
            else:  # 不一样就把获取信息里主机名 替换成 本地文件的唯一标识
                # 更改主机名+资产
                info['type'] = 'host_update'
                info['hostname'] = cert
                print(info)

        # 发送给api
        ctime = time.time()
        key = gen_key(ctime)
        res = requests.post(
            url=self.asset_api,
            params={'key': key, 'ctime': ctime},
            data=json.dumps(info).encode('utf-8'),
            headers={'Content-Type': 'application/json'}
        )
        # print(res.text)
        print("--------------------------------")
        print(type(res.json()))

        response = res.json()
        print(response.get('status'))
        if response.get('status'):
            # 采集的数据成功进入数据库 把主机名存到本地标识文件
            with open(cert_path, 'w', encoding='utf-8') as f:
                f.write(response.get('hostname'))